/**
 * 微博超话自动签到插件 V1.6.1
 * Created by MapleX
 * popup.js - 弹出窗口脚本
 */

document.addEventListener('DOMContentLoaded', () => {
  const statusMessage = document.getElementById('statusMessage');
  const startButton = document.getElementById('startCheckIn');
  const topicInput = document.getElementById('topicInput');
  const addTopicBtn = document.getElementById('addTopic');
  const topicList = document.getElementById('topicList');
  const addCurrentTopicBtn = document.getElementById('addCurrentTopic');
  const exportTopicsBtn = document.getElementById('exportTopics');
  const importTopicsBtn = document.getElementById('importTopics');
  const importFileInput = document.getElementById('importFile');
  const autoCheckTime = document.getElementById('autoCheckTime');
  const saveTimeBtn = document.getElementById('saveTime');
  const autoCheckSwitch = document.getElementById('autoCheckSwitch');
  const timeInputGroup = document.getElementById('timeInputGroup');
  const stopButton = document.getElementById('stopCheckIn');

  // 获取超话标题的函数
  async function getTopicTitle(topicId) {
    return new Promise((resolve) => {
      let timeoutId;
      
      chrome.tabs.create(
        { 
          url: `https://weibo.com/p/${topicId}/super_index`,
          active: false 
        }, 
        (tab) => {
          timeoutId = setTimeout(() => {
            chrome.tabs.remove(tab.id);
            resolve('未知超话');
          }, 10000);
          
          function listener(tabId, changeInfo, updatedTab) {
            if (tabId === tab.id && changeInfo.status === 'complete') {
              chrome.tabs.sendMessage(tab.id, { action: 'getTopicTitle' }, (response) => {
                clearTimeout(timeoutId);
                chrome.tabs.remove(tab.id);
                chrome.tabs.onUpdated.removeListener(listener);
                
                if (response && response.title) {
                  resolve(response.title);
                } else {
                  resolve('未知超话');
                }
              });
            }
          }
          chrome.tabs.onUpdated.addListener(listener);
        }
      );
    });
  }

  // 显示签到状态和列表
  function updateDisplay() {
    chrome.storage.local.get(['status'], (result) => {
      if (result.status) {
        statusMessage.textContent = result.status;
        statusMessage.className = 'status ' + 
          (result.status.includes('成功') ? 'success' : 'error');
      }
    });
  }

  // 修改显示已保存的超话列表函数
  function updateTopicList() {
    chrome.storage.local.get(['savedTopics', 'topicTitles'], (result) => {
      const topics = result.savedTopics || [];
      const titles = result.topicTitles || {};
      
      // 更新计数
      document.getElementById('topicCount').textContent = `${topics.length}个`;
      
      if (topics.length > 0) {
        // 反转数组顺序，使最新添加的显示在最上面
        topicList.innerHTML = [...topics].reverse().map(topic => `
          <div class="list-item topic-item">
            <span>${titles[topic] || '未知超话'}</span>
            <span class="topic-id">${topic}</span>
            <span class="delete-btn" data-id="${topic}">×</span>
          </div>
        `).join('');
      } else {
        topicList.innerHTML = '<div class="list-item">暂未添加超话</div>';
      }
    });
  }

  // 添加超话
  addTopicBtn.addEventListener('click', async () => {
    const topicId = topicInput.value.trim();
    if (!topicId) return;

    statusMessage.textContent = '正在获取超话信息...';
    statusMessage.className = 'status';
    
    try {
      const title = await getTopicTitle(topicId);
      
      chrome.storage.local.get(['savedTopics', 'topicTitles'], (result) => {
        const topics = result.savedTopics || [];
        const titles = result.topicTitles || {};
        
        if (!topics.includes(topicId)) {
          topics.push(topicId);
          titles[topicId] = title;
          
          chrome.storage.local.set({ 
            savedTopics: topics,
            topicTitles: titles 
          }, () => {
            updateTopicList();
            topicInput.value = '';
            statusMessage.textContent = '添加成功！';
            statusMessage.className = 'status success';
          });
        } else {
          statusMessage.textContent = '该超话已添加！';
          statusMessage.className = 'status error';
        }
      });
    } catch (error) {
      statusMessage.textContent = '获取超话信息失败！';
      statusMessage.className = 'status error';
    }
  });

  // 删除超话
  topicList.addEventListener('click', (e) => {
    if (e.target.classList.contains('delete-btn')) {
      const topicId = e.target.dataset.id;
      chrome.storage.local.get(['savedTopics', 'topicTitles'], (result) => {
        const topics = result.savedTopics || [];
        const titles = result.topicTitles || {};
        
        const newTopics = topics.filter(t => t !== topicId);
        delete titles[topicId];
        
        chrome.storage.local.set({ 
          savedTopics: newTopics,
          topicTitles: titles 
        }, updateTopicList);
      });
    }
  });

  // 添加获取当前页面超话信息的数
  async function getCurrentPageTopic() {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    const currentTab = tabs[0];
    
    // 检查是否在超话页面
    if (!currentTab.url.includes('weibo.com/p/') || !currentTab.url.includes('/super_index')) {
      statusMessage.textContent = '当前页面不是超话页面！';
      statusMessage.className = 'status error';
      return null;
    }

    // 从URL中提取超话ID
    const topicId = currentTab.url.match(/\/p\/([^/]+)/)?.[1];
    if (!topicId) {
      statusMessage.textContent = '无法获取超话ID！';
      statusMessage.className = 'status error';
      return null;
    }

    // 获取超话标题
    return new Promise((resolve) => {
      chrome.tabs.sendMessage(currentTab.id, { action: 'getTopicTitle' }, (response) => {
        if (response && response.title) {
          resolve({
            id: topicId,
            title: response.title
          });
        } else {
          resolve(null);
        }
      });
    });
  }

  // 添加当前页面超话按钮点击事件
  addCurrentTopicBtn.addEventListener('click', async () => {
    const topicInfo = await getCurrentPageTopic();
    if (!topicInfo) return;

    chrome.storage.local.get(['savedTopics', 'topicTitles'], (result) => {
      const topics = result.savedTopics || [];
      const titles = result.topicTitles || {};
      
      if (!topics.includes(topicInfo.id)) {
        topics.push(topicInfo.id);
        titles[topicInfo.id] = topicInfo.title;
        
        chrome.storage.local.set({ 
          savedTopics: topics,
          topicTitles: titles 
        }, () => {
          updateTopicList();
          statusMessage.textContent = '当前超话添加成功！';
          statusMessage.className = 'status success';
        });
      } else {
        statusMessage.textContent = '该超话已添加！';
        statusMessage.className = 'status error';
      }
    });
  });

  // 初始显示
  updateTopicList();
  updateDisplay();

  // 添加检查签到状态的函数
  function checkCheckInStatus() {
    chrome.storage.local.get(['isCheckingIn'], (result) => {
      const isRunning = result.isCheckingIn || false;
      
      // 根据运行状态设置按钮
      startButton.style.opacity = isRunning ? '0.5' : '1';
      startButton.style.pointerEvents = isRunning ? 'none' : 'auto';
      stopButton.classList.toggle('active', isRunning);
      
      // 如果正在运行，显示提示
      if (isRunning) {
        statusMessage.textContent = '签到正在进行中...';
        statusMessage.className = 'status success';
      }
    });
  }

  // 修改开始签到按钮点击事件
  startButton.addEventListener('click', () => {
    chrome.storage.local.get(['savedTopics', 'isCheckingIn'], (result) => {
      const topics = result.savedTopics || [];
      const isRunning = result.isCheckingIn || false;
      
      if (isRunning) {
        statusMessage.textContent = '已有签到程序在运行中！';
        statusMessage.className = 'status error';
        return;
      }
      
      if (topics.length === 0) {
        statusMessage.textContent = '请先添加需要签到的超话！';
        statusMessage.className = 'status error';
        return;
      }
      
      // 设置运行状态
      chrome.storage.local.set({ 
        isCheckingIn: true 
      }, () => {
        // 更新按钮状态
        stopButton.classList.add('active');
        startButton.style.opacity = '0.5';
        startButton.style.pointerEvents = 'none';
        
        chrome.runtime.sendMessage({ 
          action: 'startCheckIn',
          topics: topics
        });
        statusMessage.textContent = '开始签到流程...';
        statusMessage.className = 'status success';
      });
    });
  });

  // 修改停止签到按钮点击事件
  stopButton.addEventListener('click', () => {
    chrome.storage.local.set({ 
      isCheckingIn: false 
    }, () => {
      chrome.runtime.sendMessage({ 
        action: 'stopCheckIn'
      });
      
      // 恢复按钮状态
      stopButton.classList.remove('active');
      startButton.style.opacity = '1';
      startButton.style.pointerEvents = 'auto';
      
      statusMessage.textContent = '已停止签到！';
      statusMessage.className = 'status error';
    });
  });

  // 修改存储变化监听器
  chrome.storage.onChanged.addListener((changes, namespace) => {
    if (namespace === 'local') {
      if (changes.status) {
        // 当签到完成时，恢复按钮状态
        if (changes.status.newValue === '所有超话签到完成！' || 
            changes.status.newValue === '签到已停止') {
          chrome.storage.local.set({ 
            isCheckingIn: false 
          }, () => {
            stopButton.classList.remove('active');
            startButton.style.opacity = '1';
            startButton.style.pointerEvents = 'auto';
          });
        }
        updateDisplay();
      }
      
      // 监听运行状态变化
      if (changes.isCheckingIn) {
        const isRunning = changes.isCheckingIn.newValue;
        stopButton.classList.toggle('active', isRunning);
        startButton.style.opacity = isRunning ? '0.5' : '1';
        startButton.style.pointerEvents = isRunning ? 'none' : 'auto';
      }
    }
  });

  // 初始化时检查签到状态
  checkCheckInStatus();

  // 修改导出功能，使用 CSV 格式
  async function exportToCSV() {
    try {
      const result = await chrome.storage.local.get(['savedTopics', 'topicTitles']);
      const topics = result.savedTopics || [];
      const titles = result.topicTitles || {};

      // 准备 CSV 内容
      const csvContent = [
        // CSV 头部
        ['超话ID', '超话名称'],
        // CSV 数据行
        ...topics.map(id => [id, titles[id] || '未知超话'])
      ]
        .map(row => row.map(cell => `"${cell}"`).join(','))
        .join('\n');

      // 创建 Blob
      const blob = new Blob(['\ufeff' + csvContent], { 
        type: 'text/csv;charset=utf-8;' 
      });
      
      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.setAttribute('href', url);
      link.setAttribute('download', `微博超话列表_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '')}.csv`);
      document.body.appendChild(link);
      
      // 触发下载
      link.click();
      
      // 清理
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
      statusMessage.textContent = '导出成功！';
      statusMessage.className = 'status success';
    } catch (error) {
      console.error('导出失败:', error);
      statusMessage.textContent = '导出失败！';
      statusMessage.className = 'status error';
    }
  }

  // 修改导入功能，支持 CSV 格式
  async function importFromCSV(file) {
    try {
      const text = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = e => resolve(e.target.result);
        reader.onerror = reject;
        reader.readAsText(file, 'UTF-8');
      });

      // 解析 CSV
      const rows = text.split('\n')
        .map(row => row.split(',')
        .map(cell => cell.trim().replace(/^"|"$/g, ''))); // 移除引号
      
      // 跳过标题行
      const dataRows = rows.slice(1);

      // 获取现有数据
      const result = await chrome.storage.local.get(['savedTopics', 'topicTitles']);
      const existingTopics = result.savedTopics || [];
      const existingTitles = result.topicTitles || {};

      // 处理导入的数据
      const newTopics = [];
      const newTitles = {};
      
      for (const row of dataRows) {
        if (row.length >= 2) {
          const [topicId, topicTitle] = row;
          if (topicId && !existingTopics.includes(topicId)) {
            newTopics.push(topicId);
            if (topicTitle) {
              newTitles[topicId] = topicTitle;
            }
          }
        }
      }

      // 合并数据
      const updatedTopics = [...existingTopics, ...newTopics];
      const updatedTitles = { ...existingTitles, ...newTitles };

      // 保存更新后的数据
      await chrome.storage.local.set({
        savedTopics: updatedTopics,
        topicTitles: updatedTitles
      });

      updateTopicList();
      statusMessage.textContent = `成功导入 ${newTopics.length} 个新超话！`;
      statusMessage.className = 'status success';
    } catch (error) {
      console.error('导入失败:', error);
      statusMessage.textContent = '导入失败！请检查文件格式是否正确。';
      statusMessage.className = 'status error';
    }
  }

  // 修改导出按钮事件监听器
  exportTopicsBtn.addEventListener('click', exportToCSV);

  // 修改文件输入接受类型
  document.getElementById('importFile').accept = '.csv';

  // 修改导入按钮事件监听器
  importTopicsBtn.addEventListener('click', () => {
    importFileInput.click();
  });

  // 文件选择事件
  importFileInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (file) {
      importFromCSV(file);
      // 清除选择的文件，允许重复导入相同文件
      e.target.value = '';
    }
  });

  // 加载保存的时间设置
  function loadTimeSetting() {
    chrome.storage.local.get(['autoCheckInTime'], (result) => {
      if (result.autoCheckInTime) {
        autoCheckTime.value = result.autoCheckInTime;
      } else {
        // 默认设置为 12:00
        autoCheckTime.value = '12:00';
      }
    });
  }

  // 保存时间设置
  saveTimeBtn.addEventListener('click', () => {
    const timeValue = autoCheckTime.value;
    if (timeValue) {
      chrome.storage.local.set({ 
        autoCheckInTime: timeValue 
      }, () => {
        // 更新定时任务
        chrome.runtime.sendMessage({ 
          action: 'updateCheckInTime',
          time: timeValue
        });
        
        statusMessage.textContent = '自动签到时间已更新！';
        statusMessage.className = 'status success';
      });
    }
  });

  // 加载自动签到设置
  function loadAutoCheckSettings() {
    chrome.storage.local.get(['autoCheckEnabled', 'autoCheckInTime'], (result) => {
      // 设置开关状态
      autoCheckSwitch.checked = result.autoCheckEnabled || false;
      // 显示/隐藏时间设置
      timeInputGroup.style.display = result.autoCheckEnabled ? 'flex' : 'none';
      
      // 设置时间
      if (result.autoCheckInTime) {
        autoCheckTime.value = result.autoCheckInTime;
      } else {
        autoCheckTime.value = '12:00';
      }
    });
  }

  // 开关状态改变事件
  autoCheckSwitch.addEventListener('change', () => {
    const enabled = autoCheckSwitch.checked;
    timeInputGroup.style.display = enabled ? 'flex' : 'none';
    
    chrome.storage.local.set({ 
      autoCheckEnabled: enabled 
    }, () => {
      if (enabled) {
        // 开启时立即设置定时任务
        chrome.runtime.sendMessage({ 
          action: 'updateAutoCheck',
          enabled: true,
          time: autoCheckTime.value
        });
        statusMessage.textContent = '自动签到已开启！';
      } else {
        // 关闭时清除定时任务
        chrome.runtime.sendMessage({ 
          action: 'updateAutoCheck',
          enabled: false
        });
        statusMessage.textContent = '自动签到已关闭！';
      }
      statusMessage.className = 'status success';
    });
  });

  // 修改保存时间按钮事件
  saveTimeBtn.addEventListener('click', () => {
    const timeValue = autoCheckTime.value;
    if (timeValue) {
      chrome.storage.local.set({ 
        autoCheckInTime: timeValue 
      }, () => {
        chrome.runtime.sendMessage({ 
          action: 'updateAutoCheck',
          enabled: true,
          time: timeValue
        });
        
        statusMessage.textContent = '自动签到时间已更新！';
        statusMessage.className = 'status success';
      });
    }
  });

  // 初始加载设置
  loadAutoCheckSettings();
}); 